import 'package:flutter/material.dart';
import 'package:flutter_project/config/app_bar_view.dart';
import 'package:flutter_project/config/loading_toast.dart';
import 'package:flutter_project/user/user_login/user_log_off_page.dart';
import 'package:flutter_project/user/user_login/user_login_view.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../common/privacy/dialog_common_view.dart';
import '../common/route_page/route_name.dart';
import '../common/utils/cache_file_utils.dart';
import '../config/theme_color.dart';
import '../config/web_page.dart';
import 'contact_us.dart';

class AccountManagePage extends StatefulWidget {
  final String title;

  const AccountManagePage({this.title = '', super.key});

  @override
  State<AccountManagePage> createState() => _AccountManagePageState();
}

class _AccountManagePageState extends State<AccountManagePage> {
  ValueNotifier<int> totalSize = ValueNotifier<int>(0);
  String aboutUs = '关于我们';
  String clearCache = '清除缓存';
  String cancelAccount = '注销账号';
  Color lineColor = ThemeColor.lineE8e8e8Color;

  @override
  Widget build(BuildContext context) {
    return CommonAppWidget.navAppBar(
      title: widget.title,
      childWidget: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                const SizedBox(height: 20),
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 20, vertical: 0),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(0),
                  ),
                  child: Column(
                    children: [
                      InkWell(
                        onTap: () {
                          RouteNames.push(ContactUsPage(
                            title: aboutUs,
                          ));
                        },
                        child: getListItem(name: aboutUs),
                      ),
                      Divider(
                        height: 1,
                        color: lineColor,
                      ),
                      InkWell(
                        onTap: () {
                          RouteNames.push(
                            const WebPage(
                              url: 'https://preview-app.pixverseai.com/',
                              title: '官网体验',
                            ),
                          );
                        },
                        child: getListItem(name: '官网体验'),
                      ),
                      getLineColor(lineColor),
                      ValueListenableBuilder(
                          valueListenable: totalSize,
                          builder:
                              (BuildContext context, int value, Widget? child) {
                            String sizeStr = CacheFileUtil.formatSize(
                                double.parse(value.toString()));
                            return getItem(
                                leftName: clearCache,
                                rightName: sizeStr,
                                tapAction: () {
                                  handleClearCache(context);
                                });
                          }),
                      getLineColor(lineColor),
                      InkWell(
                        onTap: () {
                          RouteNames.push(UserLoginOff());
                        },
                        child: getListItem(name: cancelAccount),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          GestureDetector(
            onTap: () {
              loginOutAction();
            },
            child: Container(
              margin: const EdgeInsets.only(left: 35, right: 35, bottom: 35),
              alignment: Alignment.center,
              height: 45,
              decoration: BoxDecoration(
                  color: ThemeColor.mainColor,
                  borderRadius: BorderRadius.circular(25)),
              child: const Text(
                '退出登录',
                style: TextStyle(
                    fontSize: 14,
                    color: Colors.white,
                    fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ],
      ),
    );
  }

//退出登录
  loginOutAction() {
    clearLocalStorage();
    RouteNames.openAndRemovedUntilWidget(const UserLoginView());
  }

  //清除本地存储数据
  clearLocalStorage() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.remove('token');
    sharedPreferences.remove('nickName');
  }

  Widget getListItem({
    required String name,
  }) {
    return Row(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 16),
          child: Text(
            name,
          ),
        ),
        const Spacer(),
        Icon(
          Icons.arrow_forward_ios_rounded,
          size: 14,
          color: ThemeColor.grayB5B5B5Color,
        ),
      ],
    );
  }

  Widget getItem({
    String leftName = '',
    Function? tapAction,
    String rightName = '',
  }) {
    return GestureDetector(
      onTap: () {
        if (tapAction != null) {
          tapAction();
        }
      },
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(vertical: 16),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              leftName,
              style: const TextStyle(fontSize: 14),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  rightName,
                  style: TextStyle(
                    fontSize: 14,
                    color: ThemeColor.grayB5B5B5Color,
                  ),
                ),
                Icon(
                  Icons.arrow_forward_ios_rounded,
                  size: 14,
                  color: ThemeColor.grayB5B5B5Color,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget getLineColor(Color color) {
    return Divider(
      height: 1,
      color: color,
    );
  }

  @override
  void initState() {
    super.initState();
    getFileSize();
  }

  handleClearCache(BuildContext context) {
    ConfirmAlertDialog.showView(context,
        title: '提示',
        content: '清除缓存会删除您的数据，确定要删除吗',
        isShowCancelBtn: true, rightAction: () {
      ensureClear();
    });
  }

  ensureClear() async {
    try {
      if (totalSize.value <= 0) {
        toast('没有缓存可清理');
        return;
      }

      /// 执行清除缓存
      await CacheFileUtil.clear();

      /// 更新缓存
      await getFileSize();
      toast('缓存清除成功');
    } catch (e) {
      toast(e.toString());
    }
  }

  Future<void> getFileSize() async {
    /// 获取缓存大小
    int size = await CacheFileUtil.total();

    /// 复制变量
    totalSize.value = size;
  }
}
